package com.piece.core.authentication.provider;

import com.piece.core.authentication.exception.UserPasswordRetryLimitExceedException;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.util.async.AsyncManager;
import com.piece.core.framework.util.cache.CacheFactory;
import com.piece.core.web.properties.SecurityProperties;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ProviderUtil {

    public static void authLoginCount(CacheFactory cacheFactory, SecurityProperties properties, String key) throws UserPasswordRetryLimitExceedException {
        AtomicInteger retryCount = cacheFactory.get().get(key, AtomicInteger.class);
        if (null == retryCount) {
            retryCount = new AtomicInteger(0);
            cacheFactory.get().set(key, retryCount);
        }
        int maxRetry = Convert.toInt(properties.getValidation().getRetry());
        int interval = Convert.toInt(properties.getValidation().getInterval());
        if (retryCount.incrementAndGet() > maxRetry) {
            if (retryCount.get() == (maxRetry + 1)) {
                // 清空登陆次数统计
                AsyncManager.getInstance().execute(new TimerTask() {
                    @Override
                    public void run() {
                        cacheFactory.get().delete(key);
                    }
                }, interval, TimeUnit.MINUTES);
            }
            throw new UserPasswordRetryLimitExceedException(maxRetry, interval);
        }
        cacheFactory.get().set(key, retryCount);
    }
}
